package com.supostacks.ase;

import cn.hutool.core.codec.Base32;
import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;

import java.nio.charset.StandardCharsets;

public class PasswordUtils {
    public static String encrypt(String plainText, String secretKey) {
        byte[] bytes = getBytes(secretKey);
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, bytes);
        byte[] encrypt = aes.encrypt(plainText);
        return Base64.encode(encrypt);
    }

    public static String decrypt(String cipherText, String secretKey) {
        byte[] decode = Base64.decode(cipherText);
        byte[] bytes = getBytes(secretKey);
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, bytes);
        return aes.decryptStr(decode);
    }

    private static byte[] getBytes(String secretKey) {
        byte[] bytes = secretKey.getBytes(StandardCharsets.UTF_8);
        if (bytes.length != 32) {
            byte[] newBytes = new byte[32];
            if (bytes.length < 32) {
                System.arraycopy(bytes, 0, newBytes, 0, bytes.length);
            }
            bytes = newBytes;
        }
        return bytes;
    }
}
